package com.yiwenup.leetcode.offer;

import com.yiwenup.leetcode.TreeNode;

import java.util.Stack;

/**
 * https://leetcode-cn.com/problems/er-cha-shu-de-jing-xiang-lcof/
 **/
public class No027 {
    /**
     * 执行用时：0 ms, 在所有 Java 提交中击败了100.00%的用户
     * 内存消耗：35.8 MB, 在所有 Java 提交中击败了42.00%的用户
     */
    public TreeNode mirrorTree(TreeNode root) {
        if (root == null) return null;
        TreeNode left = mirrorTree(root.right);
        TreeNode right = mirrorTree(root.left);
        root.left = left;
        root.right = right;

        return root;
    }

    /**
     * 执行用时：1 ms, 在所有 Java 提交中击败了8.65%的用户
     * 内存消耗：35.8 MB, 在所有 Java 提交中击败了48.93%的用户
     */
    public TreeNode mirrorTree2(TreeNode root) {
        if (root == null) return null;
        Stack<TreeNode> stack = new Stack<TreeNode>() {{
            add(root);
        }};

        TreeNode tmp = null;
        while (!stack.isEmpty()) {
            TreeNode node = stack.pop();
            if (node.left != null) stack.push(node.left);
            if (node.right != null) stack.push(node.right);

            tmp = node.left;
            node.left = node.right;
            node.right = tmp;
        }

        return root;
    }
}
